package Service;

import Data.MassageData;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

public class SendFile {
    private String filename;

    public SendFile(String filename) {
        this.filename = filename;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public MassageData sendToFile() throws IOException {
        MassageData massageData = new MassageData();
        byte[] t = null;
        File file = new File(filename);
        if (file != null)
        {
            byte[] buffer = new byte[1024*5];
            t = new byte[(int) file.length()];
            InputStream is = Files.newInputStream(file.toPath());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            while ((len = is.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            t = bos.toByteArray();

            String filename = null;
            if (file != null) {
                filename = file.getName();
                int dotIndex = filename.lastIndexOf('.');
                if (dotIndex > 0 && dotIndex < filename.length() - 1) {
                    massageData.setBytes(t);
                }
            }
        }
        return massageData;
    }
//        byte[] buffer=new byte[1024*5];
//        FileInputStream fis=new FileInputStream(filename);
//        int index=0;
//        while(true)
//        {
//            int len=fis.read(buffer);
//            if(len==-1)
//            {
//                break;
//            }
//            byte[] chunk= Arrays.copyOf(buffer,len);
//            event massage=new event();
//            massage.setType(MassageType.Send_File);
//            FileData fileData=new FileData();
//            fileData.setIndex(index);
//            fileData.setBytes(chunk);
//            massage.setT(fileData);
//            new SendMassage().sendMassage(massage);
//            index++;
//            System.out.println(index);
//        }
//        fis.close();

}
